<template>
    <el-container v-loading="loading" style="height: 100%;width: 100%;">
        <el-main ref="table-main">
            <el-table
                    :data="tableData"
                    ref="singleTable"
                    class="custom-table"
                    :header-row-class-name="'custom-head-row'"
                    :header-cell-class-name="'custom-head-column'"
                    style="width: 100%"
                    :empty-text="emptyText"
                    :row-class-name="className"
                    :row-key="getRowKey"
                    :select-on-indeterminate="false"
                    @select="handleSelect"
                    @select-all="handleSelectAll"
                    :height="tableHeight"
                    :max-height="tableHeight"
                    v-elScroll="overBackground"
            >
                <slot name="top"></slot>
                <el-table-column
                        v-for="v in columns"
                        :key="v.id"
                        :prop="v.field"
                        :label="v.title || v.field"
                        align="center"
                        :min-width="v.width || 160"
                >
                    <template slot-scope="scope">
                        <CuPopover
                                :data="(v.renderer?v.renderer(scope.row):scope.row[v.field])"
                                align="center"
                                v-if="!v.tooltip"
                        >
                        </CuPopover>
                        <span v-else v-html="v.renderer?v.renderer(scope.row):scope.row[v.field]"></span>
                    </template>
                </el-table-column>
                <slot name="end"></slot>
            </el-table>
        </el-main>
    </el-container>
</template>
<script>
import CuPopover from '@/common/CuPopover';
// {
//     field: '对应key',
//     title: '列头',
//     width: '120px',
//     renderer: (row) => {//自定义显示
//          return row;
//     }
// }
export default {
  name: 'DynamicTable',
  components: {
    CuPopover,
  },
  data() {
    return {
      emptyText: ' ',
      loading: false,
      tableHeight: null,
      cols: this.columns,
      tableData: this.list,
      pageSelection: {},
      multipleSelection: [],
    };
  },
  props: {
    className: {
      type: Function,
      default() {
        return () => {
        };
      },
    },
    columns: {
      type: Array,
      required: true,
      default() {
        return [];
      },
    },
    list: {
      type: Array,
      required: true,
      default() {
        return [];
      },
    },
    currentPage: Number
  },
  watch: {
    list(val) {
      this.tableData = val;
      this.$refs.singleTable.clearSelection();
      this.$nextTick(() => {
        if (this.pageSelection[this.currentPage]) {
          this.pageSelection[this.currentPage].forEach(item => {
            let find = val.find(v => {
              return v.id === item;
            });
            if (find) {
              this.$refs.singleTable.toggleRowSelection(find)
            }
          })
        }
      })
    },
    columns(val) {
      this.cols = val;
    }
  },
  methods: {
    overBackground(fixed) {
      let BCR = document.body.getBoundingClientRect();
      fixed.style.backgroundSize=BCR.width+'px '+BCR.height+'px';
      this.$nextTick(() => {
        let { x, y, width, height } = fixed.getBoundingClientRect();
        x |= 0;
        y |= 0;
        width |= 0;
        height |= 0;
        fixed.style.backgroundPosition = (-x)+'px '+(-y)+'px';
      })
    },
    isOverlapped(element) {
      let document = element.ownerDocument;
      let { x, y, width, height } = element.getBoundingClientRect();
      x |= 0;
      y |= 0;
      width |= 0;
      height |= 0;

      let elements = [
        document.elementFromPoint(x+1, y+1),
        document.elementFromPoint(x + width-1, y+1),
        document.elementFromPoint(x+1, y + height-1),
        document.elementFromPoint(x + width-1, y + height-1)
      ];
      return elements.filter((el) => el !== null).some((el) => el !== element && !element.contains(el));
    },
    getRowKey(row) {
      return row.id;
    },
    handleSelect(selection, row) {
      if (!this.pageSelection[this.currentPage]) {
        this.pageSelection[this.currentPage] = [];
      }
      this.pageSelection[this.currentPage] = selection.map(item => {
        return item.id
      });
      this.changeMultipleSelection();
    },
    handleSelectAll(rows) {
      if (!this.pageSelection[this.currentPage]) {
        this.pageSelection[this.currentPage] = [];
      }
      this.pageSelection[this.currentPage] = rows.map(item => {
        return item.id
      });
      this.changeMultipleSelection();
    },
    changeMultipleSelection() {
      let list = [];
      for (let k in this.pageSelection) {
        this.pageSelection[k].forEach(next => {
          list.push(next);
        })
      }

      this.multipleSelection = list;
      this.$emit('selection-change', this.multipleSelection);
    },
    exportFun() {
      var html = '';
      let url = APIObj.origin + '/workBench/export';
      var obj = {
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        sqlStatement: this.sqlStatement,
        databaseId: this.databaseId,
      };

      var form = document.createElement('form');
      form.setAttribute('method', 'POST');
      form.setAttribute('action', url);
      var $form = $(form);
      for (var k in obj) {
        html += '<input type=\'hidden\' name=\'' + k + '\' value=\'' + obj[k] + '\'/>';
      }
      $form.append(html).appendTo('body');
      form.submit();
      $(form).remove();
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.tableHeight = this.$refs['table-main'].$el.getBoundingClientRect().height;
    });
  },
};
</script>
<style lang="less" scoped></style>
